import JSZip from 'jszip'
import { FileLoader } from 'three'
import { DirBlobDataItem } from './entities'

export class RoomZIPLoader {
  private fileLoader: FileLoader

  /**预定的blob地址前缀， 这里的地址相当于别名，并非指url */
  private static BLOB_PATH_PREFIX = 'blob:/'

  public constructor() {
    this.fileLoader = new FileLoader()
  }


  //#region 加载文件
  private loadUrl_arrayBuffer(url: string): Promise<string | ArrayBuffer> {
    return this.fileLoader.setResponseType('arraybuffer').loadAsync(url)
  }

  //#endregion 加载文件

  //#region 解压文件
  public async loadZipUrl(url: string): Promise<DirBlobDataItem[]> {
    const zip = new JSZip()

    // 文件夹-文件夹下所有的文件名列表
    const dirName_fileNamesMap = new Map<string, string[]>()

    // 文件夹名 - 文件夹下所有文件相关的blobmap
    const dirBlobDataItemList: DirBlobDataItem[] = []

    const arrayBuffer = await this.loadUrl_arrayBuffer(url)

    await zip.loadAsync(arrayBuffer)

    // 可见文件都是平铺的
    console.log(zip.files)

    // 遍历zip.files, 据观察其排列已经有序，文件夹总是在前面前面，在文件夹内的文件跟在后面
    let nowDirName: string = ''
    Object.keys(zip.files).forEach((fileName) => {
      const file = zip.files[fileName]
      // console.log(fileName, file)
      if (file.dir) {
        dirName_fileNamesMap.set(fileName, [])
        nowDirName = fileName
      } else {
        if (dirName_fileNamesMap.has(nowDirName)) {
          dirName_fileNamesMap.get(nowDirName)?.push(fileName)
        } else {
          console.error('没有对应的文件夹')
        }
      }
    })

    console.log(dirName_fileNamesMap)
    const dirNameList = Array.from(dirName_fileNamesMap.keys())

    for (const dirName of dirNameList) {
      const blobPath_blobUrlMap = new Map<string, string>()
      const fileNames = dirName_fileNamesMap.get(dirName)

      if (!fileNames) {
        console.error('没有对应dirName的文件')
        continue
      }

      for (const fileName of fileNames) {
        const file = zip.files[fileName]
        const blob = await file.async('blob')

        // 生成blob地址和bloburl并记录其映射
        const blobPath = RoomZIPLoader.BLOB_PATH_PREFIX + fileName
        const blobURL = URL.createObjectURL(blob)
        blobPath_blobUrlMap.set(blobPath, blobURL)
      }

      const dirBlobDataItem = new DirBlobDataItem(dirName, blobPath_blobUrlMap)
      dirBlobDataItemList.push(dirBlobDataItem)
    }

    return dirBlobDataItemList
  }

  //#endregion 解压文件

  //#region 解析整理文件

  //#endregion 解析整理文件
}
